﻿Public MustInherit Class GameBase
    Implements IGame

#Region "variables"

    Public Const PROCESS_ALL_ACCESS As Long = &H1F0FFF

    Private m_Name As String = String.Empty
    Private m_ProcessName As String = String.Empty
    Private m_IsRunning As Boolean = False

    Protected m_Processes() As Process = Nothing

#End Region

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="pName">进程名</param>
    Public Sub New(ByVal pName As String)
        Me.New(pName, pName)
    End Sub

    Public Sub New(ByVal name As String, ByVal pName As String)
        Me.Name = name
        Me.ProcessName = pName

        Me.Init()
    End Sub

    Public Property Name() As String Implements IGame.Name
        Get
            Return Me.m_Name
        End Get
        Set(ByVal value As String)
            Me.m_Name = value
        End Set
    End Property


    Public Property ProcessName() As String Implements IGame.ProcessName
        Get
            Return Me.m_ProcessName
        End Get
        Set(ByVal value As String)
            Me.m_ProcessName = value
        End Set
    End Property

    Public Property IsRunning() As Boolean Implements IGame.IsRunning
        Get
            Return Me.m_IsRunning
        End Get
        Set(ByVal value As Boolean)
            Me.m_IsRunning = value
        End Set
    End Property

    Public Sub Init() Implements IGame.Init
        Me.m_Processes = Diagnostics.Process.GetProcessesByName(Me.ProcessName)

        For Each item As Process In Me.m_Processes
            item.EnableRaisingEvents = True
            AddHandler item.Exited, AddressOf Me.Process_Exited
        Next

        Me.IsRunning = (Me.m_Processes.Length > 0)

        'Console.WriteLine("{0} 调用 Init，IsRunning: {1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), Me.m_IsRunning)
    End Sub

    Public MustOverride Sub Modify() Implements IGame.Modify

    Protected Overridable Sub Process_Exited(ByVal sender As Object, ByVal e As EventArgs)
        Console.WriteLine("{0} - {1} exited.", DirectCast(sender, Process).Id, Me.Name)
        Me.Init()
    End Sub

End Class
